package zkdemo;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

public class ZkMonitor {

    static ZooKeeper zk;
    {
        try {
            zk = new ZooKeeper("127.0.0.1:2181", 20000, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class MyWatch implements Watcher {

        public void process(WatchedEvent event) {
            System.out.println("当前对象的" + this.toString());
            System.out.println("监听到事件," + Thread.currentThread().getName() + "-" + Thread.currentThread().getId() + "-" +  event.getType());
            if(event.getType().equals(Event.EventType.NodeChildrenChanged)) {
                System.out.println("子节点被改变了");
                // 再注册一个监听器
                try {
                    zk.getChildren("/server", this, null);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Monitor implements Runnable {


        public void run() {
            // 模拟线程来获取监听信息
            try {
                // 注册监听
                zk.getChildren("/server", new MyWatch(), null);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        new ZkMonitor();
        new Thread(new Monitor(), "线程1").start();
        new Thread(new Monitor(), "线程2").start();
        while(true) {

        }
    }



}


